import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
// 导入静态数据 - 已禁用
// import { outboundListData, outboundDetailListData, customerListData } from '@/data/outbound'

// 恢复/添加 API 导入
import {
  getOutboundList as fetchOutboundList,
  getOutboundDetail as fetchOutboundDetail,
  createOutbound as createOutboundApi,
  updateOutbound as updateOutboundApi,
  updateOutboundStatus as updateOutboundStatusApi,
  pickOutbound as pickOutboundApi,
  shipOutbound as shipOutboundApi,
  getPickingTasks as fetchPickingTasks, // Keep if used
  getShippingTasks as fetchShippingTasks, // Keep if used
  getCustomerList as fetchCustomerList, // Keep if used
  exportOutbound as exportOutboundApi, // Keep if used
  getOutboundStatistics as fetchOutboundStatisticsApi // 恢复导入
} from '@/api/outbound' // Verify API path

export const useOutboundStore = defineStore('outbound', () => {
  // 状态定义
  const outboundList = ref([])
  const outboundDetail = ref(null) // Initialize as null
  const detailList = ref([]) // Keep if components use it directly
  const customerList = ref([]) // Keep if used
  const pickingTasks = ref([]) // Keep if used
  const shippingTasks = ref([]) // Keep if used
  const loading = ref(false)
  const productList = ref([]) // 添加商品列表的响应式变量
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })
  
  // 添加发货相关的状态
  const shippingList = ref([])
  const todayShippingRecords = ref([])
  const shippingStatistics = ref({
    total: 0, // Initialize with 0
    pending: 0,
    completed: 0,
    onTime: 0
  })
  
  // 出库单状态文本映射
  const getOutboundStatusText = (status) => {
    // 如果状态未定义或为null，返回默认状态文本
    if (status === undefined || status === null) {
      return '待拣货';  // 默认显示待拣货
    }
    
    const statusMap = {
      0: '已取消',      // StatusOutboundCancelled
      1: '待拣货',      // StatusOutboundWaitingPicking
      2: '待发货',      // StatusOutboundWaitingShipping
      3: '已完成'       // StatusOutboundCompleted
      // 移除之前不一致的状态
    };
    return statusMap[status] || `未知状态(${status})`;
  };
  
  // 出库单状态颜色映射
  const getOutboundStatusColor = (status) => {
    // 如果状态未定义或为null，返回默认颜色（橙色 - 待拣货）
    if (status === undefined || status === null) {
      return 'orange';  // 默认显示待拣货的颜色
    }
    
    const colorMap = {
      0: 'red',      // 已取消 - 红色
      1: 'orange',   // 待拣货 - 橙色
      2: 'blue',     // 待发货 - 蓝色
      3: 'green'     // 已完成 - 绿色
      // 移除之前不一致的状态
    };
    return colorMap[status] || 'gray';
  };

  // 获取出库单列表
  async function getOutboundList(params = {}) {
    try {
      loading.value = true

      // --- 使用真实 API 调用 ---
      const response = await fetchOutboundList({
          page: pagination.value.current,
          pageSize: pagination.value.pageSize,
         ...params
      });
       // --- API 调用结束 ---

      console.log('API返回原始数据:', response);

      // 检查响应格式并相应处理
      if (response && response.code === 0 && response.data) {
        // 标准API响应格式: {code: 0, data: {list: [], page: 1, ...}}
        if (Array.isArray(response.data.list)) {
          outboundList.value = response.data.list;
          pagination.value = {
            current: response.data.page || pagination.value.current,
            pageSize: response.data.size || pagination.value.pageSize,
            total: response.data.total || 0
          }
          
          // 处理每个出库单记录，将snake_case转换为camelCase
          outboundList.value = outboundList.value.map(item => ({
            ...item,
            // 转换基本字段
            id: item.id,
            code: item.code,
            warehouseId: item.warehouse_id,
            warehouseName: item.warehouse?.name || '未知仓库',
            customerId: item.customer_id,
            customerName: item.customer?.name || '未知客户',
            customerContact: item.customer?.contact || '-',
            createTime: item.created_at,
            updateTime: item.updated_at,
            createdBy: item.user?.nickname || item.user?.username || '未知',
            
            // 计算货物数量和总金额
            totalQuantity: Array.isArray(item.items) ? item.items.reduce((sum, product) => sum + (product.quantity || 0), 0) : 0,
            totalAmount: Array.isArray(item.items) ? item.items.reduce((sum, product) => sum + ((product.unit_price || 0) * (product.quantity || 0)), 0) : 0,
            
            // 添加状态文本以便直接显示
            statusText: getOutboundStatusText(item.status)
          }));
          
          console.log('处理后的出库单数据:', outboundList.value);
          
          // 添加成功提示
          const message = outboundList.value.length > 0 ? '出库单列表获取成功' : '暂无出库单数据';
          Message.success(message);
          
          return {
            list: outboundList.value,
            total: response.data.total,
            page: response.data.page,
            pageSize: response.data.size
          };
        } else {
          Message.error('获取出库单列表失败: 返回数据格式错误');
          outboundList.value = [];
          pagination.value.total = 0;
          return null;
        }
      } else if (Array.isArray(response)) {
        // 直接返回数组格式
        outboundList.value = response;
        pagination.value.total = response.length;
        // 添加成功提示
        const message = outboundList.value.length > 0 ? '出库单列表获取成功' : '暂无出库单数据';
        Message.success(message);
        
        // 处理每个出库单记录，将snake_case转换为camelCase
        outboundList.value = outboundList.value.map(item => ({
          ...item,
          // 转换基本字段
          id: item.id,
          code: item.code,
          warehouseId: item.warehouse_id,
          warehouseName: item.warehouse?.name || '未知仓库',
          customerId: item.customer_id,
          customerName: item.customer?.name || '未知客户',
          customerContact: item.customer?.contact || '-',
          createTime: item.created_at,
          updateTime: item.updated_at,
          createdBy: item.user?.nickname || item.user?.username || '未知',
          
          // 计算货物数量和总金额
          totalQuantity: Array.isArray(item.items) ? item.items.reduce((sum, product) => sum + (product.quantity || 0), 0) : 0,
          totalAmount: Array.isArray(item.items) ? item.items.reduce((sum, product) => sum + ((product.unit_price || 0) * (product.quantity || 0)), 0) : 0,
          
          // 添加状态文本以便直接显示
          statusText: getOutboundStatusText(item.status)
        }));
        
        console.log('处理后的出库单数据:', outboundList.value);
        return {
          list: outboundList.value,
          total: outboundList.value.length,
          page: 1,
          pageSize: outboundList.value.length
        };
      } else {
        // 其他格式，尝试处理
        Message.error('获取出库单列表失败: 不支持的数据格式');
        outboundList.value = [];
        pagination.value.total = 0;
        return null;
      }
    } catch (error) {
      console.error('获取出库单列表失败:', error);
      Message.error('获取出库单列表时发生错误');
      outboundList.value = [];
      pagination.value.total = 0;
      throw error; // Rethrow
    } finally {
      loading.value = false;
    }
  }

  // 获取出库单详情
  async function getOutboundDetail(id) {
    if (!id) {
      throw new Error('出库单ID不能为空');
    }

    outboundDetail.value = null;
    productList.value = [];

    try {
      const response = await fetchOutboundDetail(id);
      if (!response || response.code !== 0 || !response.data) {
        throw new Error('获取出库单详情失败：' + (response?.message || '数据为空'));
      }

      const data = response.data;
      console.log('出库单详情原始数据:', data);

      // 处理基本信息
      outboundDetail.value = {
        ...data,
        orderType: data.type,
        createdTime: data.created_at, // 从created_at映射到createdTime
        expectedShippingDate: data.expected_shipping_date || '未设置', // 添加默认值处理
        remark: data.note, // 从note映射到remark
        createdBy: data.user?.nickname || data.user?.username || '未知',
        customerName: data.customer?.name || '未知',
        customerCode: data.customer?.code || '',
        customerContact: data.customer?.contact || '',
        customerPhone: data.customer?.phone || '',
        customerAddress: data.customer?.address || '未设置',
        warehouseName: data.warehouse?.name || '未知',
      };

      // 确保items数据正确处理
      if (Array.isArray(data.items)) {
        outboundDetail.value.items = data.items.map(item => ({
          ...item,
          productCode: item.cargo?.code || '',
          productName: item.cargo?.name || '',
          specification: item.cargo?.spec || '',
          unit: item.cargo?.unit || ''
        }));
      } else {
        console.warn('出库单详情中没有有效的items数组');
        outboundDetail.value.items = [];
      }

      // 处理产品列表 (用于发货等操作界面使用)
      if (Array.isArray(data.items)) {
        productList.value = data.items.map(item => ({
          ...item,
          // 从cargo对象中正确提取产品信息
          productCode: item.cargo?.code || '',
          productName: item.cargo?.name || '',
          specification: item.cargo?.spec || '',
          unit: item.cargo?.unit || '',
          // 使用正确的字段名映射
          orderQuantity: item.quantity || 0,
          pickedQuantity: item.picked_quantity || 0,
          shippedQuantity: item.shipped_quantity || 0,
          // 设置默认的发货数量为已拣货数量减去已发货数量
          shippingQuantity: Math.max(0, (item.picked_quantity || 0) - (item.shipped_quantity || 0)),
          status: item.shipped_quantity > 0 ? 'SHIPPED' : 'PICKED',
          // 初始化差异值
          variance: 0
        }));
        
        // 计算每个产品的差异值
        productList.value.forEach(item => {
          item.variance = item.shippingQuantity - item.orderQuantity;
        });
      }

      console.log('处理后的出库单详情:', outboundDetail.value);
      console.log('处理后的产品列表:', productList.value);

      return outboundDetail.value;
    } catch (error) {
      console.error('获取出库单详情失败:', error);
      throw new Error(error.message || '获取出库单详情失败');
    }
  }

  // 创建出库单 (切换到 API)
  async function createOutbound(data) {
    try {
      loading.value = true
      // --- 使用真实 API 调用 ---
      const response = await createOutboundApi(data)
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0) {
        Message.success('创建出库单成功')
        // getOutboundList(); // Optionally refresh list
        return response.data
      } else {
        Message.error(response.message || '创建出库单失败')
        return null
      }
    } catch (error) {
      console.error('创建出库单失败:', error)
      Message.error('创建出库单失败')
      throw error // Rethrow
    } finally {
      loading.value = false
    }
  }

  // 更新出库单 (切换到 API)
  async function updateOutbound(id, data) {
     if (!id) return null;
    try {
      loading.value = true
      // --- 使用真实 API 调用 ---
      const response = await updateOutboundApi(id, data)
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0) {
        Message.success('更新出库单成功')
         // getOutboundDetail(id); // Optionally refresh detail
        return response.data
      } else {
        Message.error(response.message || '更新出库单失败')
        return null
      }
    } catch (error) {
      console.error('更新出库单失败:', error)
      Message.error('更新出库单失败')
      throw error // Rethrow
    } finally {
      loading.value = false
    }
  }

  // 更新出库单状态
  async function updateOutboundStatus(id, status) {
    if (!id) {
      console.error('updateOutboundStatus: 未提供出库单ID');
      Message.error('操作失败：无效的出库单ID');
      return null;
    }

    // 确保ID为字符串格式
    const orderId = String(id);
    // 将status转换为字符串格式，因为后端需要字符串格式的状态码
    const statusStr = String(status);
    
    console.log(`准备更新出库单状态：ID=${orderId}, 状态码=${statusStr}`);

    try {
      loading.value = true;
      
      console.log(`updateOutboundStatus: 调用API更新订单 ${orderId} 的状态为: ${statusStr}`);

      // 调用API，发送字符串格式的状态码
      const response = await updateOutboundStatusApi(orderId, statusStr);
      console.log('API响应:', response);

      if (response && response.code === 0) {
        Message.success('出库单状态更新成功');
        // 可以选择性地在这里更新 Store 中的 outboundDetail 状态，以便 UI 立即响应
        if (outboundDetail.value && outboundDetail.value.id === id) {
            outboundDetail.value.status = status; // 更新本地状态为数字状态码
        }
        return response.data || true;
      } else {
        const errorMsg = response?.message || '更新出库单状态失败';
        console.error('更新状态失败:', errorMsg, response);
        Message.error(errorMsg);
        return null;
      }
    } catch (error) {
      console.error('更新出库单状态失败:', error);
      let errorMsg = '更新出库单状态失败';
      
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
        console.error('服务器返回错误:', error.response.data);
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      // 显示更详细的错误信息
      console.error('错误详情:', {
        url: error.config?.url || '未知',
        method: error.config?.method || '未知',
        status: error.response?.status || '未知',
        data: error.response?.data || '未知'
      });
      
      Message.error(errorMsg);
      return null;
    } finally {
      loading.value = false;
    }
  }

  // 执行拣货操作 (确认使用 API 和状态码 0)
  async function pickOutbound(id, data) {
    if (!id || !data || (!data.details && !data.items) || 
        (data.details && data.details.length === 0) || 
        (data.items && data.items.length === 0)) {
      Message.error('无效的拣货数据');
      return null;
    }

    // 转换数据格式 - 统一字段名
    const requestData = {
      items: data.items ? data.items.map(item => ({
        order_item_id: item.order_item_id,
        location_id: item.location_id,
        picked_quantity: item.picked_quantity,
        batch_no: item.batch_no || ''
      })) : data.details.map(detail => ({
        order_item_id: detail.detailId || detail.order_item_id,
        location_id: detail.locationId || detail.location_id,
        picked_quantity: detail.pickedQuantity || detail.picked_quantity,
        batch_no: detail.batchNo || detail.batch_no || ''
      }))
    };

    console.log('发送到后端的拣货数据:', requestData);

    try {
      loading.value = true;
      const response = await pickOutboundApi(id, requestData);

      // 使用后端API的成功状态码 0
      if (response && response.code === 0) {
        Message.success((typeof response.data === 'string' && response.data) || response.message || '拣货操作成功');
        // getOutboundDetail(id); // Backend should update status, maybe refresh detail here
        return response.data || true;
      } else {
        const errorMsg = response?.message || '拣货操作失败，请检查数据后重试';
        Message.error(errorMsg);
        return null;
      }
    } catch (error) {
      console.error('拣货操作失败:', error);
      const errorMsg = error.response?.data?.message || error.message || '拣货操作失败，服务器响应异常';
      Message.error(errorMsg);
      return null;
    } finally {
      loading.value = false;
    }
  }

  // 发货操作
  async function shipOutbound(outboundId, shippingData) {
    try {
      // 参数验证
      if (!outboundId) {
        throw new Error('出库单ID不能为空');
      }

      if (!shippingData || !Array.isArray(shippingData.items) || shippingData.items.length === 0) {
        throw new Error('发货商品不能为空');
      }

      // 验证必填字段
      if (!shippingData.tracking_number) {
        throw new Error('物流单号不能为空');
      }

      if (!shippingData.carrier) {
        throw new Error('承运商不能为空');
      }

      // 验证发货数量
      for (const item of shippingData.items) {
        if (!item.shipped_quantity || item.shipped_quantity <= 0) {
          throw new Error('发货数量必须大于0');
        }
      }

      // 设置默认值
      const submitData = {
        ...shippingData,
        shipping_cost: shippingData.shipping_cost || 0,
        shipped_time: shippingData.shipped_time || new Date().toISOString(),
        note: shippingData.note || ''
      };

      // 调用发货 API
      const response = await shipOutboundApi(outboundId, submitData);

      if (response.code !== 0) {
        throw new Error(response.message || '发货失败');
      }

      // 刷新出库单详情
      await getOutboundDetail(outboundId);

      return true;
    } catch (error) {
      console.error('发货操作失败:', error);
      throw error;
    }
  }

  // 完成发货操作
  async function completeOutboundShipping(outboundId, requestData) {
    try {
      // 参数验证
      if (!outboundId) {
        throw new Error('出库单ID不能为空');
      }

      if (!requestData || !Array.isArray(requestData.items) || requestData.items.length === 0) {
        throw new Error('发货商品不能为空');
      }

      // 验证必填字段
      if (!requestData.tracking_number) {
        throw new Error('物流单号不能为空');
      }

      if (!requestData.carrier) {
        throw new Error('承运商不能为空');
      }

      // 验证发货数量
      for (const item of requestData.items) {
        if (!item.shipped_quantity || item.shipped_quantity <= 0) {
          throw new Error('发货数量必须大于0');
        }
      }

      // 同时包含多种可能的字段名格式，覆盖所有可能性
      const submitData = {
        tracking_number: requestData.tracking_number,
        carrier: requestData.carrier,
        shipping_cost: requestData.shipping_cost || 0,
        shipped_time: requestData.shipped_time || new Date().toISOString(),
        note: requestData.note || '',
        complete: true, // 标记为完成发货
        items: requestData.items.map(item => ({
          OrderItemID: item.item_id, // 字段名形式1
          order_item_id: item.item_id, // 字段名形式2
          item_id: item.item_id, // 原始字段名
          shipped_quantity: item.shipped_quantity,
          note: item.note || ''
        }))
      };
      
      console.log('完成发货请求参数:', JSON.stringify(submitData));
      
      const response = await shipOutboundApi(outboundId, submitData);

      if (response.code !== 0) {
        throw new Error(response.message || '完成发货失败');
      }

      // 刷新出库单详情
      await getOutboundDetail(outboundId);

      return response;
    } catch (error) {
      console.error('完成发货操作失败:', error);
      throw error;
    }
  }

  // 获取客户列表 (切换到 API, 需要后端和 API 文件实现)
  async function getCustomerList(params = {}) {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      const response = await fetchCustomerList(params); // Assuming API exists
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0) {
        customerList.value = response.data.list || []; // Adjust based on API response
        return response.data;
      } else {
        Message.error(response.message || '获取客户列表失败');
        return null;
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
      Message.error('获取客户列表失败');
      throw error; // Rethrow
    } finally {
      loading.value = false;
    }
  }

  // 获取待拣货任务列表 (切换到 API, 需要后端实现)
  async function getPickingTasks() {
    try {
      loading.value = true;
       // --- 使用真实 API 调用 ---
      const response = await fetchPickingTasks(); // Assuming API exists
       // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

       // 使用后端API的成功状态码 0
      if (response.code === 0) {
        pickingTasks.value = response.data || [];
        return response.data;
      } else {
        Message.error(response.message || '获取待拣货任务失败');
        return null;
      }
    } catch (error) {
      console.error('获取待拣货任务失败:', error);
      Message.error('获取待拣货任务失败');
      throw error; // Rethrow
    } finally {
      loading.value = false;
    }
  }

  // 获取待发货任务列表 (切换到 API, 需要后端实现)
  async function getShippingTasks() {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      const response = await fetchShippingTasks(); // Assuming API exists
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0) {
        shippingTasks.value = response.data || [];
        return response.data;
      } else {
        Message.error(response.message || '获取待发货任务失败');
        return null;
      }
    } catch (error) {
      console.error('获取待发货任务失败:', error);
      Message.error('获取待发货任务失败');
      throw error; // Rethrow
    } finally {
      loading.value = false;
    }
  }

  // 获取出库统计数据
  async function getOutboundStatistics() {
    try {
      // 使用前端计算，基于当前出库单列表
      if (outboundList.value.length === 0) {
        // 如果列表为空，先获取列表数据
        await getOutboundList();
      }
      
      console.log('使用本地数据计算统计信息，当前列表长度:', outboundList.value.length);
      
      // 计算不同状态的订单数量 - 使用正确的状态编码
      const pendingPicking = outboundList.value.filter(item => item.status === 1).length;
      const pendingShipping = outboundList.value.filter(item => item.status === 2).length;
      const completed = outboundList.value.filter(item => item.status === 3).length;
      const cancelled = outboundList.value.filter(item => item.status === 0).length;
      
      // 计算今日相关数据
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      // 今日发货数量 - 查找已完成状态且今天更新的订单
      const shippedToday = outboundList.value.filter(item => {
        if (item.status === 3) { // 已完成
          const updateTime = item.updateTime ? new Date(item.updateTime) : null;
          return updateTime && updateTime >= today;
        }
        return false;
      }).length;
      
      // 计算异常单据数 - 修改为统计已取消的订单
      const exceptionOrders = cancelled;
      
      // 更新统计数据
      const statistics = {
        pendingPicking,
        pendingShipping,
        completed,
        cancelled,
        total: outboundList.value.length,
        shippedToday,
        exceptionOrders
      };
      
      // 更新store中的统计数据
      shippingStatistics.value = {
        total: statistics.total || 0,
        pending: statistics.pendingPicking + statistics.pendingShipping || 0,
        completed: statistics.completed || 0,
        onTime: statistics.shippedToday || 0,
        pendingPicking: statistics.pendingPicking || 0,
        pendingShipping: statistics.pendingShipping || 0,
        completed: statistics.completed || 0,
        shippedToday: statistics.shippedToday || 0,
        exceptionOrders: statistics.exceptionOrders || 0
      };
      
      console.log('计算的统计数据:', statistics);
      console.log('更新后的统计状态:', shippingStatistics.value);
      
      return statistics;
    } catch (error) {
      console.error('获取出库统计数据失败:', error);
      // 设置默认值以避免界面显示错误
      const defaultStats = {
        pendingPicking: 0,
        pendingShipping: 0,
        completed: 0,
        cancelled: 0,
        total: 0,
        shippedToday: 0,
        exceptionOrders: 0
      };
      
      shippingStatistics.value = {
        total: 0,
        pending: 0,
        completed: 0,
        onTime: 0,
        pendingPicking: 0,
        pendingShipping: 0,
        completed: 0,
        shippedToday: 0,
        exceptionOrders: 0
      };
      
      return defaultStats;
    }
  }

  // 设置出库统计数据
  function setOutboundStatistics(data) {
    if (!data) return;
    
    // 更新统计数据
    shippingStatistics.value = {
      total: data.total || 0,
      pendingPicking: data.to_pick || 0,
      pendingShipping: data.to_ship || 0,
      shipped: data.shipped || 0,
      completed: data.completed || 0,
      exceptionOrders: data.exception || 0,
      shippedToday: data.shipped_today || 0
    };
  }

  // 导出出库单 (示例, 切换到 API)
  async function exportOutbound(params) {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      const response = await exportOutboundApi(params); // Assuming API returns blob or similar
      // --- API 调用结束 ---

      // 处理文件下载
       if (response instanceof Blob) {
           // Create a link and trigger download
           const link = document.createElement('a');
           const url = window.URL.createObjectURL(response);
           link.href = url;
           // Extract filename from content-disposition header if available
           // const contentDisposition = response.headers['content-disposition'];
           // let filename = 'exported_outbound.xlsx'; // Default filename
           // if (contentDisposition) {
           //   const filenameMatch = contentDisposition.match(/filename="?(.+)"?/i);
           //   if (filenameMatch && filenameMatch.length > 1) {
           //     filename = filenameMatch[1];
           //   }
           // }
           link.download = 'exported_outbound.xlsx'; // Set a default filename for now
           document.body.appendChild(link);
           link.click();
           document.body.removeChild(link);
           window.URL.revokeObjectURL(url);
           Message.success('导出成功');
           return true;
       } else if (response.code !== 0) {
         Message.error(response.message || '导出出库单失败');
         return false;
       } else {
         // Handle cases where API returns JSON instead of blob?
         Message.error('导出失败：未收到文件数据');
         return false;
       }

    } catch (error) {
      console.error('导出出库单失败:', error);
      Message.error('导出出库单失败');
      return false; // Return false on error
    } finally {
      loading.value = false;
    }
  }

  // 获取待发货列表 (Dashboard specific?)
  async function getShippingList() { /* ... keep or remove ... */ console.log("getShippingList called"); return [];}
  // 获取客户地址 (Helper, keep if needed)
  function getCustomerAddress(customerId) { /* ... */ console.log("getCustomerAddress called for", customerId); return "Mock Address"; }
  // 获取发货统计信息 (Dashboard specific?)
  async function getShippingStatistics() { /* ... keep or remove ... */ console.warn("Duplicate getShippingStatistics called (shipping board related)"); return { total: 0, pending: 0, completed: 0, onTime: 0 }; }
  // 获取今日发货记录 (Dashboard specific?)
  async function getTodayShippingRecords() { /* ... keep or remove ... */ console.log("getTodayShippingRecords called"); return [];}

  // 确保返回所有需要暴露的状态和方法
  return {
    outboundList,
    outboundDetail,
    detailList,
    customerList,
    pickingTasks,
    shippingTasks,
    loading,
    pagination,
    productList,
    shippingList,
    todayShippingRecords,
    shippingStatistics,
    getOutboundList,
    getOutboundDetail,
    createOutbound,
    updateOutbound,
    updateOutboundStatus,
    pickOutbound,
    shipOutbound,
    completeOutboundShipping,
    getCustomerList,
    getPickingTasks,
    getShippingTasks,
    getOutboundStatistics,
    setOutboundStatistics,
    exportOutbound,
    // 添加状态映射函数
    getOutboundStatusText,
    getOutboundStatusColor
  }
}) 